package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.SMSUtils;
import com.itheima.reggie.common.ValidateCodeUtils;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession httpSession){
        //获取手机号
        String phone = user.getPhone();
        if (phone!=null) {
            //生成随机的4位验证码
            Integer code1 = ValidateCodeUtils.generateValidateCode(4);
            String code = code1.toString();
            //调用阿里云提供的短信服务APi完成发送短信

            //签名  , 模板Code   手机号，  验证码
            SMSUtils.sendMessage("坤仔牛逼","",phone,code);
            //需要将生成的验证码保存到Session里面去
            httpSession.setAttribute(phone,code);
            return R.success("手机验证码发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 移动端用户登录
     * 登录校验
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){

        //从map里面获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从Session中获取保存的验证码
        String codeSeesion = session.getAttribute("phone").toString();

        //进行验证码的比对(页面提交的验证码和Seesion保存的验证码进行比对)
        if (code.equals(codeSeesion)==true){
            //比对成功说明登录成功

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(phone!=null,User::getPhone,phone);
            User one = userService.getOne(queryWrapper);
            if (one==null){
            //判断当前手机号是否为新用户，如果是新用户就自动保存完成注册
            User user = new User();
            user.setPhone(phone);
            userService.save(user);
            }
            return R.success(one);
        }

        return R.error("登录失败");
    }

}
